package cn.com.v2.controller;

import cn.com.v2.common.base.BaseController;
import cn.com.v2.common.config.V2Config;
import cn.com.v2.common.domain.AjaxResult;
import cn.com.v2.common.domain.ResultTable;
import cn.com.v2.common.domain.Tablepar;
import cn.com.v2.model.Project;
import cn.com.v2.model.ProjectData;
import cn.com.v2.model.SysFile;
import cn.com.v2.model.vo.ProjectVo;
import cn.com.v2.model.vo.SysFileVo;
import cn.com.v2.service.IProjectDataService;
import cn.com.v2.service.IProjectService;
import cn.com.v2.service.ISysFileService;
import cn.com.v2.util.ConvertUtil;
import cn.com.v2.util.SaTokenUtil;
import cn.com.v2.util.SnowflakeIdWorker;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ltx
 */
@RestController
@RequestMapping("/api/project")
public class ProjectController extends BaseController {
    @Autowired
    private ISysFileService iSysFileService;
    @Autowired
    private V2Config v2Config;
    @Autowired
    private IProjectService iProjectService;
    @Autowired
    private IProjectDataService iProjectDataService;


    @ApiOperation(value = "分页跳转", notes = "分页跳转")
    @GetMapping("/list")
    @ResponseBody
    public ResultTable list(Tablepar tablepar) {
        Page<Project> page = new Page<Project>(tablepar.getPage(), tablepar.getLimit());
        IPage<Project> iPages = iProjectService.page(page, new LambdaQueryWrapper<Project>().eq(Project::getCreateUserId, SaTokenUtil.getUserId()));
        ResultTable resultTable = new ResultTable();
        resultTable.setData(iPages.getRecords());
        resultTable.setCode(200);
        resultTable.setCount(iPages.getTotal());
        resultTable.setMsg("获取成功");
        return resultTable;
    }


    /**
     * 新增保存
     *
     * @param
     * @return
     */
    //@Log(title = "项目表新增", action = "111")
    @ApiOperation(value = "新增", notes = "新增")
    @PostMapping("/create")
    @ResponseBody
    public AjaxResult add(@RequestBody Project project) {
        project.setCreateTime(DateUtil.now());
        project.setState(-1);
        String userId = SaTokenUtil.getUserId();
        project.setCreateUserId(userId);
        boolean b = iProjectService.save(project);
        if (b) {
            return successData(200, project).put("msg", "创建成功");
        } else {
            return error();
        }
    }


    /**
     * 项目表删除
     *
     * @param ids
     * @return
     */
    //@Log(title = "项目表删除", action = "111")
    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/delete")
    @ResponseBody
    public AjaxResult remove(String ids) {
        List<String> lista = ConvertUtil.toListStrArray(ids);
        Boolean b = iProjectService.removeByIds(lista);
        if (b) {
            return success();
        } else {
            return error();
        }
    }

    @ApiOperation(value = "修改保存", notes = "修改保存")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestBody Project project) {
        Boolean b = iProjectService.updateById(project);
        if (b) {
            return success();
        }
        return error();
    }


    @ApiOperation(value = "项目重命名", notes = "项目重命名")
    @PostMapping("/rename")
    @ResponseBody
    public AjaxResult rename(@RequestBody Project project) {

        LambdaUpdateWrapper<Project> updateWrapper = new LambdaUpdateWrapper<Project>();
        updateWrapper.eq(Project::getId, project.getId());
        updateWrapper.set(Project::getProjectName, project.getProjectName());
        Boolean b = iProjectService.update(updateWrapper);
        if (b) {
            return success();
        }
        return error();
    }


    //发布/取消项目状态
    @PutMapping("/publish")
    @ResponseBody
    public AjaxResult updateVisible(@RequestBody Project project) {
        if (project.getState() == -1 || project.getState() == 1) {

            LambdaUpdateWrapper<Project> updateWrapper = new LambdaUpdateWrapper<Project>();
            updateWrapper.eq(Project::getId, project.getId());
            updateWrapper.set(Project::getState, project.getState());
            Boolean b = iProjectService.update(updateWrapper);
            if (b) {
                return success();
            }
            return error();
        }
        return error("警告非法字段");
    }


    @ApiOperation(value = "获取项目存储数据", notes = "获取项目存储数据")
    @GetMapping("/getData")
    @ResponseBody
    public AjaxResult getData(String projectId, ModelMap map) {
        Project project = iProjectService.getById(projectId);

        ProjectData blogText = iProjectDataService.getProjectid(projectId);
        if (blogText != null) {
            ProjectVo projectVo = new ProjectVo();
            BeanUtils.copyProperties(project, projectVo);
            projectVo.setContent(blogText.getContent());
            return AjaxResult.successData(200, projectVo).put("msg", "获取成功");
        }
        return AjaxResult.successData(200, null).put("msg", "无数据");

    }


    @ApiOperation(value = "保存项目数据", notes = "保存项目数据")
    @PostMapping("/save/data")
    @ResponseBody
    public AjaxResult saveData(ProjectData data) {

        Project project = iProjectService.getById(data.getProjectId());
        if (project == null) {
            return error("没有该项目ID");
        }
        ProjectData projectData = iProjectDataService.getOne(new LambdaQueryWrapper<ProjectData>().eq(ProjectData::getProjectId, project.getId()));
        if (projectData != null) {
            data.setId(projectData.getId());
            iProjectDataService.updateById(data);
            return success("数据保存成功");
        } else {
            iProjectDataService.save(data);
            return success("数据保存成功");
        }
    }

    /**
     * 上传文件
     *
     * @param object 文件流对象
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestBody MultipartFile object) throws IOException {
        String fileName = object.getOriginalFilename();
        //默认文件格式
        String suffixName = v2Config.getDefaultFormat();
        String mediaKey = "";
        Long filesize = object.getSize();
        //文件名字
        String fileSuffixName = "";
        if (fileName.lastIndexOf(".") != -1) {//有后缀
            suffixName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            //mediaKey=MD5.create().digestHex(fileName);
            mediaKey = SnowflakeIdWorker.getUUID();
            fileSuffixName = mediaKey + suffixName;
        } else {//无后缀
            //取得唯一id
            //mediaKey = MD5.create().digestHex(fileName+suffixName);
            mediaKey = SnowflakeIdWorker.getUUID();
            //fileSuffixName=mediaKey+suffixName;
        }
        String virtualKey = FileController.getFirstNotNull(v2Config.getXnljmap());
        String absolutePath = v2Config.getXnljmap().get(FileController.getFirstNotNull(v2Config.getXnljmap()));
        SysFile sysFile = new SysFile();
        sysFile.setId(SnowflakeIdWorker.getUUID());
        sysFile.setFileName(fileSuffixName);
        sysFile.setFileSize(Integer.parseInt(filesize + ""));
        sysFile.setFileSuffix(suffixName);
        sysFile.setCreateTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
        String filepath = DateUtil.formatDate(new Date());
        sysFile.setRelativePath(filepath);
        sysFile.setVirtualKey(virtualKey);
        sysFile.setAbsolutePath(absolutePath.replace("file:", ""));
        iSysFileService.saveOrUpdate(sysFile);
        File desc = FileController.getAbsoluteFile(v2Config.getFileurl() + File.separator + filepath, fileSuffixName);
        object.transferTo(desc);
        SysFileVo sysFileVo = BeanUtil.copyProperties(sysFile, SysFileVo.class);
        sysFileVo.setFileurl(v2Config.getHttpurl() + sysFile.getVirtualKey() + "/" + sysFile.getRelativePath() + "/" + sysFile.getFileName());
        return successData(200, sysFileVo);
    }


}
